﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LuZhouLaoJiao;
using MySql.Data.MySqlClient;
using System.Data.SQLite;
using System.IO;

namespace LuZhouLaoJiao
{
    public partial class Load : Form
    {

        Timer dingshi;
        Timer cleanConfig;
        bool isFormChanged = false;
        bool isPwdChanged = false;
        bool isLoadFinished = false;

        public Load()
        {
            InitializeComponent();

            string ds = "./data.db";
            if (!System.IO.File.Exists(ds))
            {
                SQLiteConnection.CreateFile(ds);
                SQLiteConnection conn = new SQLiteConnection("Data Source=./data.db");
                SQLiteCommand comm = new SQLiteCommand();
                conn.Open();
                comm = conn.CreateCommand();
                comm.Connection = conn;

                comm.CommandText = "create table if not exists batch_info(pici_id varchar(32) not null primary key," +
                    "suandu float(5,3),jianceren varchar(24), laiyuan varchar(32),riqi varchar(12),shijian varchar(20),beizhu text,tijiao varchar(10));";
                comm.ExecuteNonQuery();

                comm.CommandText = "create table if not exists sample(yangben_id integer primary key," +
                    "yangbenhao int(3), pici_id varchar(32),jiaochi varchar(20),suandu float(5,3),jiqi varchar(20),shijian varchar(12),"
                    +"laiyuan varchar(32), beizhu text);";
                comm.ExecuteNonQuery();

                comm.CommandText = "create table if not exists user(id integer primary key," +
                    "name varchar(20), pwd varchar(32), isadmin varchar(2));";
                comm.ExecuteNonQuery();

                conn.Close();
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            Global.userName = tbUserName.Text.ToString();
            string userPassword = tbPassword.Text.ToString();

            if (Global.userName == "")
            {
                MessageBox.Show("登录名不能为空");
            }
            else
            {
                if (userPassword == "")
                {
                    MessageBox.Show("密码不能为空！");
                }
                else
                {
                    if (cbAutoLog.Checked && dingshi.Enabled)
                    {
                        return;
                    }
                    //MessageBox.Show("P:" + userPassword + Global.isExist(Global.userName, userPassword).ToString());
                    if ((Global.isExist(Global.userName, Global.MD5(userPassword)) == false) && (Global.isExist(Global.userName, userPassword) == false))
                    {
                        MessageBox.Show("登录名和密码不对,请重新输入!!!");
                        return;
                    }
                    else
                    {
                        if (cbRemPwd.Checked)
                        {
                            Global.setRegeditValue("IsRemPwd", "YES");
                            Global.setRegeditValue("CurrentUser", tbUserName.Text.ToString());
                            if (isPwdChanged)
                            {
                                Global.setRegeditValue("CurrentPwd", Global.MD5(tbPassword.Text.ToString().Trim()));
                            }
                        }
                        else
                        {
                            Global.setRegeditValue("IsRemPwd", "NO");
                            Global.setRegeditValue("CurrentUser", "");
                            Global.setRegeditValue("CurrentPwd", "");

                            Global.setRegeditValue("IsAutoLog", "NO");
                        }
                        if (cbAutoLog.Checked)
                        {
                            Global.setRegeditValue("IsAutoLog", "YES");
                        }
                        else
                        {
                            Global.setRegeditValue("IsAutoLog", "NO");
                        }
                        Global.setRegeditValue("AlreadyRunSetRemoteDB","");
                        BatchInfo batchInfo = new BatchInfo();
                        this.Hide(); 
                        batchInfo.ShowDialog();
                       // this.Close();                       
                    }
                }
            }
        }

        private void Load_Load(object sender, EventArgs e)
        {
            if (!Global.isKeyExist("FirstRunning"))
            {
//                 if (!Global.isKeyExist("AlreadySetLocalDB"))
//                 {
//                     //MessageBox.Show("未设置本地数据库.");
//                     SetLocalDatabase localDB = new SetLocalDatabase();
//                     localDB.ShowDialog();
//                 }
                if (!Global.isKeyExist("AlreadySetAdmin"))
                {
                    CreateAdminUser adminUser = new CreateAdminUser();
                    adminUser.ShowDialog(this);
                }
                //if (!Global.isKeyExist("AlreadySetRemoteDB"))
                //{
                //    //MessageBox.Show("未设置远程数据库.");
                //    if (!Global.isKeyExist("AlreadyRunSetRemoteDB")) 
                //    {
                //        SetRemoteDB remoteDB = new SetRemoteDB();
                //        remoteDB.ShowDialog();
                //    }
                //}
            }
            else
            {
                //登录成功
            }

            try
            {
                if ((Global.getRegeditValue("IsRemPwd") == "YES") && (Global.getRegeditValue("IsAutoLog") == "YES"))
                {
                    cbRemPwd.Checked = true;
                    cbAutoLog.Checked = true;
                    tbUserName.Text = Global.getRegeditValue("CurrentUser");
                    tbPassword.Text = Global.getRegeditValue("CurrentPwd");
                }
                else if ((Global.getRegeditValue("IsRemPwd") == "YES") && !(Global.getRegeditValue("IsAutoLog") == "YES"))
                {
                    cbRemPwd.Checked = true;
                    cbAutoLog.Checked = false;
                    tbUserName.Text = Global.getRegeditValue("CurrentUser");
                    tbPassword.Text = Global.getRegeditValue("CurrentPwd");
                }
                else if (!(Global.getRegeditValue("IsRemPwd") == "YES"))
                {
                    cbRemPwd.Checked = false;
                    cbAutoLog.Checked = false;
                    //tbUserName.Text = Global.getRegeditValue("CurrentUser");
                    //tbPassword.Text = Global.getRegeditValue("CurrentPwd");
                }
            }
            catch (System.NullReferenceException)
            {
            	
            }

            dingshi = new Timer();
            dingshi.Tick += new EventHandler(dingshi_Tick);
            dingshi.Interval = 3000;
            dingshi.Start();

            cleanConfig = new Timer();
            cleanConfig.Tick +=new EventHandler(cleanConfig_Tick);
            cleanConfig.Interval = 15000;
            cleanConfig.Start();

            isLoadFinished = true;
        }

        private void cbAutoLog_CheckedChanged(object sender, EventArgs e)
        {
            if (isLoadFinished)
            {
                isFormChanged = true;
                if (dingshi.Enabled)
                {
                    dingshi.Stop();
                }
            } 
        }

        private void cbRemPwd_CheckedChanged(object sender, EventArgs e)
        {
            if (isLoadFinished)
            {
                isFormChanged = true;
                if (dingshi.Enabled)
                {
                    dingshi.Stop();
                }
            }
            if (!cbRemPwd.Checked)
            {
                cbAutoLog.Checked = false;
            }
        }

        private void dingshi_Tick(object source, EventArgs e)
        {
            if (cbAutoLog.Checked)
            {
                //登录
                if (Global.getRegeditValue("CurrentUser").Trim() == tbUserName.Text.ToString().Trim())
                {
                    if (Global.getRegeditValue("CurrentPwd").Trim() == tbPassword.Text.ToString().Trim())
                    {
                        dingshi.Stop();
                        this.Hide();
                        Global.userName = tbUserName.Text.ToString().Trim();
                        BatchInfo batchInfo = new BatchInfo();
                        batchInfo.ShowDialog();
                    }
                }
            }


            if (dingshi.Enabled)
            {
                dingshi.Stop();
            }
        }

        private void cleanConfig_Tick(object source, EventArgs e)
        {
            if (tbUserName.Text.ToString().Trim() == "")
            {
                if (cleanConfig.Enabled)
                {
                    cleanConfig.Stop();
                }
                DialogResult result = MessageBox.Show("需要重新配置程序吗？", "配置程序数据", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    //清空原配置数据
                    //MessageBox.Show("qingkong");
                    Global.deleteKeyValue("AlreadyRunSetRemoteDB");
                    Global.deleteKeyValue("AlreadySetAdmin");
                    Global.deleteKeyValue("AlreadySetLocal");
                    Global.deleteKeyValue("AlreadySetLocalDB");
                    Global.deleteKeyValue("CurrentPwd");
                    Global.deleteKeyValue("CurrentUser");
                    Global.deleteKeyValue("IsAutoLog");
                    Global.deleteKeyValue("IsRemPwd");
                    Global.deleteKeyValue("localDatabase");
                    Global.deleteKeyValue("localDBPwd");
                    Global.deleteKeyValue("localDBUser");
                    Global.deleteKeyValue("localIP");

                    DialogResult rmData = MessageBox.Show("是否要删除本机上已测试数据？", "删除测试数据", MessageBoxButtons.YesNo);
                    if (rmData == DialogResult.Yes)
                    {
                        if (File.Exists("data.db"))
                        {
                            File.Delete("data.db");
                        }
                    }

                    MessageBox.Show("现在可以重新登录以进行重新配置");
                    this.Close();
                }
                else
                {
                    if (cleanConfig.Enabled)
                    {
                        cleanConfig.Stop();
                    }
                    
                }
            }
            
        }

        private void tbPassword_TextChanged(object sender, EventArgs e)
        {
            isPwdChanged = true;
        }

        private void tbUserName_TextChanged(object sender, EventArgs e)
        {
            if (isLoadFinished)
            {
                isFormChanged = true;
                if (dingshi.Enabled)
                {
                    dingshi.Stop();
                }
            }
            if (!cbRemPwd.Checked)
            {
                cbAutoLog.Checked = false;
            }
            tbPassword.Clear();
        }
    }
}
